using System;
using System.Collections.Generic;
using System.Text;
using OpenNETCF.Net;
namespace ServiceConnect
{
    public class Presenter
    {
        private View m_view;

        public Presenter(View view)
        {
            m_view = view;

            // wire up all device event handlers and update the view
            foreach(RasEntry entry in Ras.Entries)
            {
                entry.Error += new RasErrorHandler(OnRasEntryError);
                entry.RasStatus += new RasNotificationHandler(OnRasEntryStatusChange);

                m_view.AddRasEntryToList(entry);
            }

            foreach (DeviceInfo device in Ras.Devices)
            {
                m_view.AddRasDeviceToList(device);
            }

            if (Ras.ActiveConnections != null)
            {
                m_view.SetConnectionList(Ras.ActiveConnections);
            }
        }

        public void OnClearEntrySelection()
        {
            m_view.ClearEntrySelection();
        }

        public void OnSelectEntry(RasEntry entry)
        {
            m_view.SelectEntry(entry);
        }


        public void OnDial(RasEntry entry)
        {
            if (entry == null) throw new ArgumentNullException();

            m_view.DisableDialButton();

            entry.Dial(true);
        }

        void OnRasEntryStatusChange(int hConn, RasConnState State, RasError ErrorCode)
        {
            // refresh active connection list
            m_view.ClearConnectionList();

            RasConnection connection = GetConnectionByID(hConn);

            if (connection == null)
            {
                // this should never happen, but if it does, we want to know
                throw new Exception("Status Change detected on unknown connection");
            }

            m_view.SetConnectionList(Ras.ActiveConnections);

            m_view.OnRasEntryStatusChange(connection, State, ErrorCode);
        }

        void OnRasEntryError(RasEntry entry, RasError ErrorCode)
        {
            m_view.OnRasEntryError(entry, ErrorCode);
        }

        public RasConnection GetConnectionByID(int hConnection)
        {
            foreach (RasConnection connection in Ras.ActiveConnections)
            {
                if (hConnection == connection.hConnection)
                {
                    return connection;
                }
            }

            return null;
        }
    }
}
